<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Model;

use Admin\Logic\NestedSets;
use Think\Page;

class PermissionModel extends \Think\Model
{

    /**
     * 开启批量验证
     * @var bool
     */
    protected $patchValidate = true;

    /**
     * 批量验证规则
     * 1. 商品名必填
     * 2. 商品分类必填
     * 3. 品牌必填
     * 4. 供货商必填
     * 5. 市场价必填,必须是货币
     * 6. 商城价格必填,必须是货币
     * 7. 库存必填,必须是数字
     * ...
     */
    protected $_validate = [
        ['name', 'require', '权限不能为空'],
    ];

    /**
     * 开启自动完成
     * @var array
     */
    protected $_auto = [

    ];

    /**
     * 获取所有商品的列表和分页信息
     * @param array $cond
     * @return array
     */
    public function getList(array $cond = [])
    {
        $cond = array_merge(['status' => 1], $cond);
        $count = $this->where($cond)->count();
        $page_setting = C('PAGE_SETTING');
        $page = new Page($count, $page_setting['PAGE_SIZE']);
        $page->setConfig('theme', $page_setting['PAGE_THEME']);
        $page_html = $page->show();
        $rows = $this->where($cond)->page(I('get.p', 1), $page_setting['PAGE_SIZE'])->order('lft')->select();

        return compact('rows', 'page_html');
    }

    public function getPermissions()
    {
        $permissions = $this->select();
        $newPers = [];

        foreach ($permissions as $permission) {
            $newPers[] = [
                'id' => $permission['id'],
                'name' => $permission['name'],
                'parent_id' => $permission['parent_id'],
            ];
        }

        return $newPers;
    }

    public function addPermission()
    {
        unset($this->data[$this->getPk()]);
        $orm = D('MySQL', 'Logic');
        $nestedSets = new NestedSets($orm, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');
        return $nestedSets->insert($this->data['parent_id'], $this->data, 'bottom');
    }

    public function findPermission($id)
    {
        $row = $this->find($id);
        $row['permission_ids'] = $this->select();
        return $row;
    }

    public function savePermission($id)
    {
        // 判断是否修改了父级权限
        $parent_id = $this->getFieldById($id, 'parent_id');
        /*echo $parent_id;
        exit;*/
        if ($parent_id != $this->data['parent_id']) {
            $orm = D('MySQL', 'Logic');
            $nestedSets = new NestedSets($orm, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');

            if ($nestedSets->moveUnder($this->data['id'], $this->data['parent_id'], 'bottom') === false) {
                $this->error = '不能将分类移动到自身和子类中';
                return false;
            }
        }
        // 保存基本数据
        return $this->save();
    }

    public function deletePermission($id)
    {
        $this->startTrans();
        //1.删除权限的同时也要删除角色对应的权限
        $data = $this->where(['id' => $id])->field('lft,rght')->find();
        //var_dump($data);exit;
        $cond = [
            'lft' => ['egt', $data['lft']],
            'rght' => ['elt', $data['rght']]
        ];
        $permission_ids = $this->where($cond)->getField('id', true);
        //var_dump($permission_ids);exit;

        if (M('RolePermission')->where(['permission_id' => ['in', $permission_ids]])->delete() === false) {
            $this->error = '角色权限删除失败';
            $this->rollback();
            return false;
        }

        $orm = D('MySQL', 'Logic');
        $nestedSets = new NestedSets($orm, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');

        if ($nestedSets->delete($id) === false) {
            $this->error = '权限删除失败';
            $this->rollback();
            return false;
        } else {
            $this->commit();
            return true;
        }

    }
}
